package com.pnk087.servlet.chapter4;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Created by IntelliJ IDEA.
 * User: khanhpham
 * Date: 4/21/12
 * Time: 4:16 PM
 * To change this template use File | Settings | File Templates.
 */
public class DownloadServlet extends HttpServlet {
    private static String AVAILABLE_DOWNLOAD_FILE = "download/sample.xml";

    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        resp.setContentType("application/xml");
        ServletContext ctx = this.getServletContext();
        InputStream inputStream = ctx.getResourceAsStream(AVAILABLE_DOWNLOAD_FILE);
        int read = 0;
        byte[] bytes = new byte[1024];
        OutputStream outputStream = resp.getOutputStream();
        while ((read = inputStream.read(bytes)) != -1) {
            outputStream.write(bytes, 0, read);
        }
        outputStream.flush();
        outputStream.close();
        inputStream.close();
    }
}
